const { Transform } = require('stream');
const _ = require('lodash');
const utils = require('../../utils');


module.exports = function (iteratees, orders) {
  const stream = new Transform({ objectMode: true });
  if (iteratees === 'desc' || iteratees === 'asc' || iteratees === -1 || iteratees === 1) {
    orders = iteratees;
    iteratees = undefined;
  }
  orders === -1 && (orders = 'desc');
  orders === 1 && (orders = 'asc');
  const list = [];
  stream._transform = async function (chunk, encoding, callback) {
    list.push(chunk);
    callback();
  };
  stream._flush = function (callback) {
    _.orderBy(list, iteratees, orders).forEach(o => {
      stream.push(o)
    });
    callback();
  };
  stream.on('finish', function () {
    utils.debug('sortTransform [finish]');
  });

  return stream;
};